package com.example.demojpa.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonPathExtractor {

    private final JsonNode rootNode;
    private final String split;

    public JsonPathExtractor(String jsonString,String split) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        this.rootNode = objectMapper.readTree(jsonString);
        this.split = split;
    }

    public String getValue(String path) {
        String[] parts = path.split(split);
        JsonNode currentNode = rootNode;

        try {
            for (String part : parts) {
                if (part.contains("[")) {
                    // Extract array field name and index
                    String fieldName = part.substring(0, part.indexOf('['));
                    int index = Integer.parseInt(part.substring(part.indexOf('[') + 1, part.indexOf(']')));
                    currentNode = currentNode.get(fieldName).get(index);
                } else {
                    currentNode = currentNode.get(part);
                }
                if (currentNode == null) {
                    return null; // Path does not exist
                }
            }
            // Return as JSON string if object or array
            if (currentNode.isObject() || currentNode.isArray()) {
                return currentNode.toString();
            }
            // Return primitive value as a string
            if (currentNode.isValueNode()) {
                return currentNode.asText();
            }
            return null;
        } catch (Exception e) {
            return null; // Handle invalid path or data issues
        }
    }

    public int getSize(String path) {
        String[] parts = path.split(split);
        JsonNode currentNode = rootNode;

        try {
            for (String part : parts) {
                if (part.contains("[")) {
                    // Extract array field name and index
                    String fieldName = part.substring(0, part.indexOf('['));
                    int index = Integer.parseInt(part.substring(part.indexOf('[') + 1, part.indexOf(']')));
                    currentNode = currentNode.get(fieldName).get(index);
                } else {
                    currentNode = currentNode.get(part);
                }
                if (currentNode == null) {
                    return -1; // Path does not exist
                }
            }
            // Determine size based on JsonNode type
            if (currentNode.isObject()) {
                return 1; // Return 1 for objects
            } else if (currentNode.isArray()) {
                return currentNode.size(); // Return array size
            } else if (currentNode.isValueNode()) {
                return 1; // Single value
            }
            return -1; // Invalid node type
        } catch (Exception e) {
            return -1; // Handle invalid path or data issues
        }
    }

    public static void main(String[] args) {
        String json = "{\"title\":\"json在线解析（简版） -JSON在线解析\",\"json.url\":\"https://www.sojson.com/simple_json.html\",\"keywords\":\"json在线解析\",\"功能\":[\"JSON美化\",\"JSON数据类型显示\",\"JSON数组显示角标\",\"高亮显示\",\"错误提示\",{\"备注\":[\"www.sojson.com\",\"json.la\"]}],\"加入我们\":{\"qq群\":\"259217951\"}}";

        try {
            JsonPathExtractor extractor = new JsonPathExtractor(json,"_");

            // Test getValue
            System.out.println(extractor.getValue("title"));
            System.out.println(extractor.getValue("功能[5]_备注"));
            System.out.println(extractor.getValue("json.url"));

            System.out.println(extractor.getSize("功能[5]_备注"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
